var express = require("express");
var router = express.Router();
const { errorCode, successCode, config } = require('../config/config');
const utils = require('../utils/utils.js');
const createSql = require("../utils/Create_SQL");
const Db = require("../utils/db");
const expressWs = require('express-ws'); //及时通信
expressWs(router);

let clients = [];
router.ws('/chat', function (ws, req) {
    clients.push(ws);

    // 获取客户端IP
    let ip  = utils.getClientIP(req);
    ws.send(JSON.stringify({
        ...successCode[200],
        data : {
            addtime : utils.getTime('yyyy-MM-dd HH:mm:ss'),
            content : "链接成功",
            cretedUser : req.headers['user-agent'],
            ip : ip,
            count : clients.length
        }
    }));
    ws.on('message', function (msg) {
        let data = {
            addtime : utils.getTime('yyyy-MM-dd HH:mm:ss'),
            content : msg,
            cretedUser : req.headers['user-agent'],
            ip : ip,
            ID : utils.getUuid()
        }
        let sql = createSql.insert("chat").value(data).end();
        Db.query(sql);
        clients.forEach(client => {
            client.send(JSON.stringify({
                ...successCode[200],
                data : {
                    ...data,
                    count : clients.length
                }
            }));
        });
    });

    ws.on('close', function () {
        clients = clients.filter(client => client !== ws);
    });

    ws.on('error' , function(){
        console.log("链接错误")
    })
});

/**
 * @swagger
 * /api/webChat/getMessage:
 *    get:
 *      tags:
 *      - 及时通信
 *      summary: 获取最近50条消息
 *      produces:
 *      - application/json
 * */ 
router.get('/getMessage', function(req, res, next) {
    let sql = createSql.select().from("chat").order("addtime").limit(0 , 50).end();
    Db.query(sql, res).then(result => {
        if (result.code) return;
        result.forEach(v => {
            v.addtime = v.addtime ? utils.getTime(null, v.addtime) : "1997-10-15 10:00:00";
        })
        res.json({
            ...successCode[200],
            data : result
        })
    }).catch(e => {
        res.json(e)
    })
})

module.exports = router;